package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import com.sun.corba.se.impl.oa.toa.TOA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;
    @Override
    public void setVerifyCode(String phone, String code) {
        //获取key
        String key = RedisKeys.VERIFY_CODE.join(phone);
//        String key = "verify_code:" +phone;
        //设置key的生存时间
        template.opsForValue().set(key,code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);

    }

    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        return template.opsForValue().get(key);
    }

    @Override
    public String setToken(UserInfo user) {
        //使用UUID创建唯一的token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        String key = RedisKeys.USER_TOKEN.join(token);

        //设置redis 的token时间
        template.opsForValue().set(key, JSON.toJSONString(user),RedisKeys.USER_TOKEN.getTime(),TimeUnit.SECONDS);

        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        //判断token是否有值
        if (!StringUtils.hasLength(token)){
            return null;
        }
        String key = RedisKeys.USER_TOKEN.join(token);

//        System.err.println(222+""+key);
        //判断key是否存在
        if (template.hasKey(key)){
            //根据key的值获取user对象
            String user = template.opsForValue().get(key);
            //将字符串类型user对象转化为json 类型数据
            UserInfo userInfo = JSON.parseObject(user, UserInfo.class);
            //重置token时间
            template.expire(key, RedisKeys.USER_TOKEN.getTime(),TimeUnit.SECONDS);
            return userInfo;
        }

        return null;
    }
}
